//
//  YZMSeverTimeService.m
//  YZMicroStock
//
//  Created by wangminhong on 16/3/21.
//  Copyright © 2016年 cqjr. All rights reserved.
//

#import "YZMSeverTimeService.h"
#import "YZClient.h"
#import "JSONBaseDeal.h"
#import <DateTools/DateTools.h>

@interface YZMSeverTimeService()

@property (nonatomic, assign) NSTimeInterval severTime;

@end

@implementation YZMSeverTimeService

{
    
    NSTimeInterval _currentTime;
    BOOL _unNeedFetchFlag;
}

+ (instancetype)sharedService
{
    static YZMSeverTimeService *sInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sInstance = [[self alloc] init];
    });
    
    return sInstance;
}

- (id)init{
    
    self = [super init];
    if (self) {
        
        _currentTime = -1;
        _severTime = -1;
        [self fetchSeverTimeFromDefault];
    }
    return self;
}

- (void)initSeverDate{
    
    if (_severTime < 0 || !_unNeedFetchFlag || [NSDate date].timeIntervalSince1970 -_currentTime >= 60*60) {
        
        [YZClient fetchSeverTimeWithSuccess:^(NSURLResponse *response, id responseObject){
            
            YZGeneralResultModel *topModel = responseObject;
            if (topModel.success) {
                
                _severTime = [JSONBaseDeal getDoubleValue:@"currentTime" fromData:topModel.data]/1000;
                _currentTime = [[NSDate date] timeIntervalSince1970];
                [self saveSeverTimeToDefault];
                _unNeedFetchFlag = YES;
            }
            
        }failure:nil];
    }
}

- (NSTimeInterval)severTime{
    
    if (_severTime < 0) {
        
        return -1;
    }
    
    return _severTime - _currentTime + [[NSDate date] timeIntervalSince1970];
}

- (NSDate *)severDate{
    
    NSTimeInterval time = self.severTime;
    
    if (time < 0) {
        
        return [NSDate date];
    }
    
    return [NSDate dateWithTimeIntervalSince1970:time];
}

#define sYZMSeverTimeServiceForSeverDefault  @"YZMSeverTimeServiceForSeverDefault"
#define sYZMSeverTimeServiceForCurrentDefault @"sYZMSeverTimeServiceForCurrentDefault"

//添加缓存serverTime
- (void)saveSeverTimeToDefault{
    
    [[NSUserDefaults standardUserDefaults] setObject:@(_severTime) forKey:sYZMSeverTimeServiceForSeverDefault];
    [[NSUserDefaults standardUserDefaults] setObject:@(_currentTime) forKey:sYZMSeverTimeServiceForCurrentDefault];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

- (void)fetchSeverTimeFromDefault{
    
    NSNumber *number = [[NSUserDefaults standardUserDefaults] objectForKey:sYZMSeverTimeServiceForSeverDefault];
    if (number != nil) {
        
        _severTime = [number doubleValue];
        _currentTime = [[[NSUserDefaults standardUserDefaults] objectForKey:sYZMSeverTimeServiceForCurrentDefault] doubleValue];
    }
}

@end
